package com.miplus.ccrm.common;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class R<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 错误码，Success=200
     */
    private Integer code;

    /**
     * 错误提示
     */
    private String message;

    /**
     * 时间戳，长整型
     */
    private long timestamp;

    /**
     * 返回数据
     */
    private T data;

    public void SetError(EnumRCode err,String msg)
    {
        code=err.value;
        message=msg;
    }

    public void SetError(EnumRCode err)
    {
        SetError(err,err.name);
    }

    public boolean IsSuccess()
    {
        return code==EnumRCode.Success.value;
    }

    public static <T> R<T> Success(T d)
    {
        R<T> result=new R<>();
        result.setCode(EnumRCode.Success.value);
        result.setMessage(EnumRCode.Success.name);
        result.setTimestamp(System.currentTimeMillis());
        result.setData(d);
        return result;
    }

    public static <T> R<PageData<T>> SuccessPage(IPage<T> page)
    {
        R<PageData<T>> result=new R<>();
        result.setCode(EnumRCode.Success.value);
        result.setMessage(EnumRCode.Success.name);
        result.setTimestamp(System.currentTimeMillis());

        result.setData(PageData.Set(page));

        return result;
    }

    public static <T> R<T> Success()
    {
        return Success(null);
    }

    public static <T> R<T> Error(Integer Code,String Message)
    {
        R<T> result=new R<>();
        result.setCode(Code);
        result.setMessage(Message);
        result.setTimestamp(System.currentTimeMillis());
        result.setData(null);
        return result;
    }

    public static <T> R<T> Error(EnumRCode err)
    {
        return Error(err.value,err.name);
    }

    public static <T> R<T>  Error(EnumRCode err,String Message)
    {
        return Error(err.value,String.format("%s(%s)",err.name,Message));
    }

    public static <T> R<T> Error(Integer code)
    {
        return Error(code,toMessage(code));
    }

    public static String toMessage(Integer code)
    {
        for(EnumRCode p : EnumRCode.values()) {
            if(p.value==code){
                return p.name;
            }
        }
        return "-";
    }
}